package com.commonlibrary.httpframe;

import android.support.annotation.NonNull;

import com.commonlibrary.BuildConfig;
import com.commonlibrary.utils.Lg;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitManager {

    private static final long TIME_OUT_CONN = 10;
    private static final long TIME_OUT_WRITE = 10;
    private static final long TIME_OUT_READ = 10;
    private Retrofit retrofit;
    private Apis mApis;


    private RetrofitManager() {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(TIME_OUT_CONN, TimeUnit.SECONDS);//网络连接超时
        builder.readTimeout(TIME_OUT_READ, TimeUnit.SECONDS);//读取超时
        builder.writeTimeout(TIME_OUT_WRITE, TimeUnit.SECONDS);//写入超时

        builder.retryOnConnectionFailure(true);//错误重连

        //添加公共的头
        Interceptor headerInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Request.Builder newBuilder = request.newBuilder()
                        .addHeader("Accept-Encoding", "gzip")
                        .addHeader("Accept", "application/json")
                        .addHeader("Content-Type", "application/json; charset=utf-8")
                        .method(request.method(), request.body());
                Request newRequest = newBuilder.build();
                return chain.proceed(newRequest);
            }
        };
        builder.addInterceptor(headerInterceptor);

        //打印日志
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(@NonNull String message) {
                    Lg.d(message);
                }
            });
            logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logInterceptor);
        }


        retrofit = new Retrofit.Builder()
                .client(builder.build())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Apis.BASE_URL)
                .build();

        mApis = retrofit.create(Apis.class);
    }

    public Apis getApis() {
        return mApis;
    }

    private static class RetrofitHolder {
        final static RetrofitManager INSTANCE = new RetrofitManager();
    }

    public static RetrofitManager getInstance() {
        return RetrofitHolder.INSTANCE;
    }

    /**
     * 需要更改ip/域名地址时使用
     */
    public void changeBaseUrl(String baseUrl) {
        retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(baseUrl)
                .build();
        mApis = retrofit.create(Apis.class);
    }

    public <T> void subscribe(@NonNull Observable<T> observable,
                              DisposableObserver<T> observer) {
        observable.subscribeOn(Schedulers.io()).
                unsubscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe(observer);
    }
}
